package com.mishow.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.adapter.MySelectAdapter;
import com.mishow.adapter.StarFactoryAdapter;
import com.mishow.bean.PhotoVO;
import com.mishow.bean.RedsBean;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.refresh.PullPushRefreshLayout;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.SelectPhotoResponse;
import com.mishow.request.response.SelectPhotoResponse.Result;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.EmptyDataLayout;
import com.mishow.widget.MyListView;
/**
 * 作者：wei.miao <br/>
 * 描述：我的精选
 */
public class MySelectActivity extends BaseActivity implements OnRefreshListener, PullPushRefreshLayout.OnLoadListener{

	private Button btn_back;
	private TextView title_tv;
	/** 下拉刷新 **/
	private PullPushRefreshLayout refreshLayout_select;
	/** 数据为空 **/
	private EmptyDataLayout empty_select_empty;
	/** 精选列表 **/
	private MyListView list_select;
	/**
	 * 我的精选adapter
	 */
	private MySelectAdapter mSelectAdapter ;
	
	
	private ArrayList<PhotoVO> mPhotoVOs;
	
	private int pageNo = 1;
	
	private int pageSize = 10;
	
	/** 列表总条数 **/
	private int total;
	/** 是否正在网络请求中默认为false **/
	private boolean isReflesh;
	/** 刷新操作 **/
	public static final int ACTION_REFRESH = 1;
	/** 加载更多操作 **/
	public static final int ACTION_LOAD_MORE = 2;
	
	private SharedPreferencesUtil preferencesUtil;
	
	public static void intoActivity(Context context){
		
		Intent intent = new Intent(context,MySelectActivity.class);
		context.startActivity(intent);
		
	}
	@Override
	protected void initData() {
		
		mPhotoVOs = new ArrayList<PhotoVO>();
		
		preferencesUtil = new SharedPreferencesUtil(mContext);
		mSelectAdapter = new MySelectAdapter(mContext, mPhotoVOs);
		
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		
		setContentView(R.layout.activity_myselect);
		btn_back =  (Button)findViewById(R.id.btn_back);
		title_tv = (TextView)findViewById(R.id.title_tv);
		refreshLayout_select = (PullPushRefreshLayout)findViewById(R.id.refreshLayout_select);
		empty_select_empty = (EmptyDataLayout)findViewById(R.id.empty_select_empty);
		list_select = (MyListView)findViewById(R.id.list_select);
		
	}

	@Override
	protected void setAttribute() {
		
		title_tv.setText("相册");
		btn_back.setOnClickListener(onClickListener);
		
		refreshLayout_select.setOnRefreshListener(this);
		refreshLayout_select.setOnLoadListener(this);
		
		list_select.setAdapter(mSelectAdapter);
		list_select.setOnItemClickListener(onItemClickListener);
		onRefresh();
	}
	
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			
			PhotoVO photoVO = mPhotoVOs.get(position);
			StarDetailsActivity.intoActivity(mContext, photoVO.getId()+"");
		}
	};
	
	@Override
	public void onLoad() {
		if (total > mPhotoVOs.size()) {
			pageNo++;
			getMySelectFromApi(ACTION_LOAD_MORE);
		} else {
			loadCompleted();
		}
	}

	@Override
	public void onRefresh() {
		pageNo = 1;
		getMySelectFromApi(ACTION_REFRESH);
	}
	
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			default:
				break;
			}
			
		}
	};
	
	/**
	 * 服务端获取星秀列表
	 * @param action 区分刷新或加载更多
	 */
	private void getMySelectFromApi(final int action) {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		if(isReflesh){
			return ;
		}
		isReflesh = true;
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		
		params.put("userId",preferencesUtil.getUserId());
		params.put("pageNo", pageNo+"");
		params.put("pageSize", pageSize+"");

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.GET_QUERY_PHTOTPAGE);
		OnResponseListener<SelectPhotoResponse> listener = new OnResponseListener<SelectPhotoResponse>(mContext) {

			@Override
			public void onSuccess(SelectPhotoResponse response) {
				Result result = response.getBody().getResult();
				ArrayList<PhotoVO> dataList = result.getDataList();
				if (dataList != null && dataList.size() > 0) {
					total = response.getBody().getResult().getTotal();
					if (action == ACTION_REFRESH) {
						handlerRefresh(dataList);
					} else if (action == ACTION_LOAD_MORE) {
						handleLoadMore(dataList);
					}
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
				if (action == ACTION_LOAD_MORE) {
					pageNo--;
				}
			}

			@Override
			public void onCompleted() {
				isReflesh = false;
				dismissProgress();
				loadCompleted();
			}
		};
		executeRequest(new FastJsonRequest<SelectPhotoResponse>(
				Request.Method.POST, postUrl, SelectPhotoResponse.class,
				listener, listener).setParams(lastParams));

	}
	
	/**
	 * 刷新后的数据
	 * @param results
	 */
	private void handlerRefresh(ArrayList<PhotoVO> results) {
		if (results == null || results.isEmpty()) {
			mPhotoVOs.clear();
			mSelectAdapter.notifyDataSetChanged();
			empty_select_empty.setVisibility(View.VISIBLE);
		} else {
			empty_select_empty.setVisibility(View.GONE);
			mPhotoVOs.clear();
			mPhotoVOs.addAll(results);
			mSelectAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 加载更多数据 
	 * @param results
	 */
	private void handleLoadMore(ArrayList<PhotoVO> results) {
		if (results != null && !results.isEmpty()) {
			mPhotoVOs.addAll(results);
			mSelectAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 加载完成
	 */
	private void loadCompleted() {

		refreshLayout_select.setRefreshing(false);
		refreshLayout_select.setLoading(false);
		// 获取到全部数据后，则隐藏加载更多
		if (total > mPhotoVOs.size()) {
			refreshLayout_select.setCanLoadMore(true);
		} else {
			refreshLayout_select.setCanLoadMore(false);
		}
	}
}
